package com.nut.util;

public class DeptCodeUtil {

    //生成的 code，数字部分长度  A01 = 2
    public static final int NUM_LEN = 2;

    /**
     * 根据前一个code，获取同级下一个code
     * 例如:当前最大code为D01A04，下一个code为：D01A05
     *
     * @param code
     * @return
     */
    public static String nextDeptCode(String code) {

        if (StringUtils.isEmpty(code)) {
            return getMinCode();
        }

        String prefix = code.substring(0, code.length() - NUM_LEN);
        String num = code.substring(code.length() - NUM_LEN);

        if (num.equals(getMaxNum())) {
            //字母递增
            String ch;
            if (prefix.length() > 1) {
                String before = prefix.substring(0, prefix.length() - 1);
                String after = prefix.substring(prefix.length() - 1);
                ch = before + nextChar(after.charAt(0));
            } else {
                ch = String.valueOf(nextChar(prefix.charAt(0)));
            }
            return ch + getStrNum(1);
        }

        int i = Integer.valueOf(num).intValue();
        return prefix + getStrNum(++i);
    }

    /**
     * 根据父亲code,获取下级的下一个code
     * <p>
     * 例如：父亲CODE:A01
     * 当前CODE:A01B03
     * 获取的code:A01B04
     *
     * @param parentCode 上级code
     * @return
     */
    public static synchronized String getSubDeptCode(String parentCode) {
        return StringUtils.isEmpty(parentCode) ? getMinCode() : parentCode + getMinCode();
    }

    private static String getMinCode() {
        return 'A' + getStrNum(1);
    }

    private static String getStrNum(int num) {
        return String.format("%0" + NUM_LEN + "d", num);
    }

    private static String getMaxNum() {
        String max = "";
        for (int i = 0; i < NUM_LEN; i++) {
            max += "9";
        }
        return max;
    }

    private static char nextChar(char a) {
        return a == 'Z' ? 'A' : ++a;
    }

    public static void main(String[] args) {

        System.out.println(nextDeptCode(""));
        System.out.println(nextDeptCode("A02"));
        System.out.println(nextDeptCode("C05"));
        System.out.println(nextDeptCode("D23"));
        System.out.println(nextDeptCode("A01A34"));
        System.out.println(nextDeptCode("A01A99"));

//        String a01A03 = nextDeptCode("A01A03");
//
//
//        System.out.println(nextChar('D'));
//        System.out.println(nextChar('Z'));
//        System.out.println(nextChar('F'));
    }
}
